package com.hu.auth.common.aop;

import com.hu.auth.common.config.WebInterceptor;
import com.hu.auth.common.exception.CustomException;
import com.hu.auth.common.result.RCodeEnum;
import com.hu.auth.service.UserService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.lang.reflect.Method;
import java.util.List;

@Aspect
@Component
public class VerifyAop {

    @Resource
    UserService userService;

    @Pointcut("@annotation(com.hu.auth.common.aop.Verify)")
    public void point() {
    }

    // @Before("point()")
    // public boolean before(JoinPoint joinPoint) {
    //     MethodSignature signature = (MethodSignature) joinPoint.getSignature();
    //     Method method = signature.getMethod();
    //     Verify verify = method.getAnnotation(Verify.class);
    //     return verify.isOk();
    // }

    // 环绕通知,环绕增强，相当于MethodInterceptor
    // @Around("point()")
    // public Object around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
    //     MethodSignature signature = (MethodSignature) proceedingJoinPoint.getSignature();
    //     Verify verify = signature.getMethod().getAnnotation(Verify.class);
    //     // 理论上权限从redis上获取快，为了测试直接查询数据库
    //     if (!userService.getUserPerms(WebInterceptor.getUserId()).contains(verify.key())) {
    //         return R.fail().message(RCodeEnum.PERMISSION.getMessage());
    //     }
    //     return proceedingJoinPoint.proceed();
    // }

    @Before("point()")
    public void before(JoinPoint joinPoint) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        Verify verify = method.getAnnotation(Verify.class);
        List<String> userPerms = userService.getUserPerms(WebInterceptor.getUserId());
        if (!userPerms.contains(verify.key())) {
            throw new CustomException(RCodeEnum.PERMISSION.getCode(), RCodeEnum.PERMISSION.getMessage());
        }
    }

}
